/**
 * @Author: lena
 * @Date: 2021/10/17 20:11
 * @Description: 连接mysql
 * @Version: 1.0.0
 */

package mysql

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql" // 必须导入否则无法识别mysql
)

var db *sql.DB

/**
创建student结构体用于操作数据库表student
create table student (
	id int primary key,
	name varchar(20),
	age int
*/
type Student struct {
    id   int
    name string
    age  int
}

// 初始化数据库链接
func init() {
    url := "root:root@tcp(127.0.0.1:3306)/test"
    // db存在于"db/mysql/crud.go"文件中
    db, _ = sql.Open("mysql", url)
    // 尝试链接
    err := db.Ping()
    if err != nil {
        fmt.Println("ping err :", err)
        return
    }
    fmt.Println("conn success!") // conn success!
}